﻿package net.wangit.support.action;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.wangit.Element;
import net.wangit.MapList;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.context.ActionContextImpl;
import net.wangit.context.LocalContext;
import net.wangit.framework.action.OutActionResult;
import net.wangit.framework.config.MimeSettings;
import net.wangit.framework.util.ResponseWriter;
import net.wangit.view.element.ElementComponent;
import net.wangit.view.element.component.HiddenElement;
import net.wangit.view.element.util.ElementUtil;
import net.wangit.view.unit.UnitComponent;
import net.wangit.view.unit.UnitFactory;
import net.wangit.view.unit.sum.SumProcessor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 * 单元数据转Excel文件，导出对应列表的本页数据。 
 * 
 * @author watson
 * Feb 25, 2010
 */
public class Unit2ExcelAction extends DownloadAction {

	private static final Log log = LogFactory
			.getLog(net.wangit.support.action.Unit2ExcelAction.class);
	protected String unitId;
	protected UnitComponent uc;
	protected MapList data;
	protected List elements;

	public Unit2ExcelAction() {
		elements = new ArrayList();
	}

	//处理下载。
	public ActionContext execute(ActionContext ac) throws Exception {
		LocalContext lc = LocalContext.getLocalContext();
		HttpServletResponse response = lc.getHttpServletResponse();
		try {
			config(ac);
			uc.setData(data);
			SumProcessor.sum(ac, uc, null, null);
			data = uc.getData();
			doDownload(ac, response);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			ResponseWriter.write(response, "无法下载：未知的异常，请联系管理员.");
		}
		((ActionContextImpl) ac).setActionResult(new OutActionResult());
		return ac;
	}

	//下载接口。
	protected void doDownload(ActionContext ac, HttpServletResponse response)
			throws Exception {
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("unit");
		HSSFRow row = sheet.createRow(0);
		row = sheet.createRow(1);
		HSSFCellStyle headStyle = createBaseStyle(wb);
		headStyle.setFillForegroundColor((short) 22);
		headStyle.setFillPattern((short) 1);
		for (int i = 0; i < elements.size(); i++) {
			Element element = (Element) elements.get(i);
			HSSFRichTextString value = new HSSFRichTextString(element.getName());
			HSSFCell cell = row.createCell(i);
			cell.setCellValue(value);
			cell.setCellStyle(headStyle);
		}

		HSSFCellStyle dataStyle = createBaseStyle(wb);
		if (data != null) {
			for (int i = 0; i < data.size(); i++) {
				row = sheet.createRow((short) (i + 2));
				net.wangit.Row dataRow = data.getRow(i);
				for (int j = 0; j < elements.size(); j++) {
					ElementComponent ec = (ElementComponent) elements.get(j);
					String value = ElementUtil.getValueOrDefault(ac, ec,
							dataRow);
					String text = ec.getText(ac, value);
					if (text == null)
						text = "";
					HSSFCell cell = row.createCell(j);
					cell.setCellValue(new HSSFRichTextString(text));
					cell.setCellStyle(dataStyle);
				}

			}

		}
		resetSheet(ac, wb, sheet);
		String fileName = (new StringBuilder(String.valueOf(getFileName(ac))))
				.append(".xls").toString();
		String contentType = MimeSettings.getContentType("xls");
		OutputStream out = getOutputStream(response, fileName, contentType);
		wb.write(out);
		out.close();
	}

	//取得文件名称（不包含.xls）
	protected String getFileName(ActionContext ac) {
		return unitId;
	}

	//子类可覆盖此方法，重新设置已生成的sheet
	protected void resetSheet(ActionContext actioncontext,
			HSSFWorkbook hssfworkbook, HSSFSheet hssfsheet) {
	}
	
	//设置数据（data）和显示的列（elements）
	protected void config(ActionContext ac) throws Exception {
		String domain = ActionContextHelper.getActionDomain(ac);
		unitId = ActionContextHelper.getActionUnitId(ac);
		uc = UnitFactory.getUnit(ac, domain, unitId, null);
		data = uc.getData();
		for (int i = 0; i < uc.size(); i++) {
			ElementComponent ec = (ElementComponent) uc.getElement(i);
			if (!ec.isToolbarElement() && isData(ec) && ec.getShowMode() != 9
					&& ec.getShowMode() != 7 && !(ec instanceof HiddenElement))
				elements.add(ec);
		}

	}

	private HSSFCellStyle createBaseStyle(HSSFWorkbook wb) {
		HSSFCellStyle style = wb.createCellStyle();
		HSSFFont font = wb.createFont();
		font.setFontHeightInPoints((short) 9);
		style.setFont(font);
		style.setBorderTop((short) 1);
		style.setBorderBottom((short) 1);
		style.setBorderLeft((short) 1);
		style.setBorderRight((short) 1);
		return style;
	}

	private boolean isData(ElementComponent ec) {
		String name = ec.getName();
		return !"查看".equals(name) && !"修改".equals(name);
	}

}
